package com.buildings.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.JsonReader;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.buildings.R;
import com.buildings.base.BaseActivity;
import com.buildings.base.BaseApplication;
import com.buildings.bean.GeoJsonbean;
import com.buildings.bean.LocationEntity;
import com.buildings.bean.RelationTaskDbBean;
import com.buildings.bean.TaskNewBean;
import com.buildings.map.ArcGisUtil;
import com.buildings.map.TianDiMapUtils;
import com.buildings.view.FragmentDialog;
import com.esri.arcgisruntime.data.ShapefileFeatureTable;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.PolygonBuilder;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.KmlLayer;
import com.esri.arcgisruntime.layers.WebTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.BackgroundGrid;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.ogc.kml.KmlDataset;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapTableActivity extends BaseActivity {
    @BindView(R.id.gis_map)
    MapView mapView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right_text)
    TextView tvightText;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.button1)
    Button button1;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    private WebTiledLayer vectorBaseMap;
    private WebTiledLayer vectorBaseMapAnno;
    private ArcGisUtil arcGisUtil;
    private ArcGISMap map;
    // 1 线 2面 3完成
    private int type = 1;
    private String result = "";

    private Point locationPoint;
    private int i = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_map);
        ButterKnife.bind(this);
        initMap();
        initAndroidLocation();
    }

    private LocationManager locationManager;

    public void initAndroidLocation() {
        //获取定位类
        LocationDisplay locationDisplayManager = mapView.getLocationDisplay();
        locationDisplayManager.setShowLocation(true);
        locationDisplayManager.setShowLocation(true);
        locationDisplayManager.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                locationPoint = locationChangedEvent.getLocation().getPosition();
                if (i == 1) {
                    moveMapCenter(locationPoint);
                    i++;
                }
            }
        });
        locationDisplayManager.startAsync();//开始定位
    }

    private String taskId;
    private String projectId;
    private String projectName;
    private String taskName;
    private TaskNewBean taskNewBean;

    public void initMap() {
        tvTitle.setText("选择地图范围");
        if (!getIntent().hasExtra("taskId")) {
            finish();
        }
        if (!getIntent().hasExtra("projectId")) {
            finish();
        }
        taskId = getIntent().getStringExtra("taskId");
        projectId = getIntent().getStringExtra("projectId");
        projectName = getIntent().getStringExtra("projectName");
        taskName = getIntent().getStringExtra("taskName");
        if (getIntent().hasExtra("TaskNewBean")) {
            taskNewBean = (TaskNewBean) getIntent().getSerializableExtra("TaskNewBean");
        }
        if (null != taskNewBean && !TextUtils.isEmpty(taskNewBean.getMapInfos())) {
            drawableMapPoint(taskNewBean.getMapInfos());
        }
        button.setVisibility(View.GONE);
        button1.setVisibility(View.GONE);
        arcGisUtil = new ArcGisUtil(this, mapView);
        map = new ArcGISMap();

        vectorBaseMap = TianDiMapUtils.getTianDiMap(TianDiMapUtils.MapType.URL_CN_VECTORBASEMAP);
        vectorBaseMapAnno = TianDiMapUtils.getTianDiMap(TianDiMapUtils.MapType.URL_CN_VECTORBASEMAP_ANNOTATION);

        List<WebTiledLayer> vectorBaseMapLayerList = new ArrayList<>();
        vectorBaseMapLayerList.add(vectorBaseMap);
        vectorBaseMapLayerList.add(vectorBaseMapAnno);

        map.setMaxScale(TianDiMapUtils.getSCALES()[TianDiMapUtils.getSCALES().length - 1]);
        mapView.setMap(map);
        mapView.setAttributionTextVisible(false);
        mapView.setBackgroundGrid(new BackgroundGrid(Color.WHITE, Color.WHITE, 0, 2f));
        map.getOperationalLayers().addAll(vectorBaseMapLayerList);

        vectorBaseMap.loadAsync();
        vectorBaseMapAnno.loadAsync();

        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Point p = mapView.screenToLocation(new android.graphics.Point((int) e.getX(), (int) e.getY()));
                Point mapPoint = (Point) GeometryEngine.project(p, SpatialReference.create(4326));
                FragmentDialog.newInstance(mapPoint.getX(), mapPoint.getY(), taskId, projectId,projectName,taskName)
                        .show(getSupportFragmentManager(), "");
                return true;
            }

            @Override
            public boolean onRotate(MotionEvent event, double rotationAngle) {
                return false;
            }
        });

        //加载绑定的kml、kmz和shp文件
        List<RelationTaskDbBean> relationTaskDbBeans = BaseApplication.getInstance().getDaoSession().loadAll(RelationTaskDbBean.class);
        if (relationTaskDbBeans.size() != 0) {
            for (RelationTaskDbBean relationTaskDbBean : relationTaskDbBeans) {
                if (taskId.equals(relationTaskDbBean.getTaskId())) {
                    //加载文件
                    if (relationTaskDbBean.getFilePath().endsWith(".kml") || relationTaskDbBean.getFilePath().endsWith(".kmz")) {
                        File file = new File(relationTaskDbBean.getFilePath());
                        if (file.exists()) {
                            showKml(relationTaskDbBean.getFilePath());
                        }
                    } else if (relationTaskDbBean.getFilePath().endsWith(".json")) {
                        File file = new File(relationTaskDbBean.getFilePath());
                        if (file.exists()) {
                            showShp(relationTaskDbBean.getFilePath());
                        }
                    }
                }
            }
        }
    }

    private void moveMapCenter(Point point) {
        mapView.setViewpointCenterAsync(point, TianDiMapUtils.getSCALES()[16]);
    }

    String layerIndex = "1";


    @OnClick({R.id.iv_back, R.id.iv_map_mylocation})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_map_mylocation:
                if (null != locationPoint) {
                    moveMapCenter(locationPoint);
                }
                break;
        }
    }

    public void drawableMapPoint(String data) {
        if (TextUtils.isEmpty(data)) {
            return;
        }
        if (!data.contains("type||")) {
            return;
        }
        String[] typeArr = data.split("type");
        for (int i = 0; i < typeArr.length; i++) {
            if (typeArr[i].startsWith("||line:")) {
                //线
                String pointArrData = typeArr[i].substring(7);
                String[] pointArr = pointArrData.split(";");
                if (pointArr.length == 0) {
                    return;
                }
                showLine(pointArr);
            } else if (typeArr[i].startsWith("||polygon:")) {
                //面
                String pointArrData = typeArr[i].substring(10);
                String[] pointArr = pointArrData.split(";");
                if (pointArr.length == 0) {
                    return;
                }
                showPolygon(pointArr);
            }
        }
    }

    private void showLine(String[] pointArr) {
        if (pointArr.length == 0) {
            return;
        }
        List<Point> points = new ArrayList<>();
        for (int i = 0; i < pointArr.length; i++) {
            String[] pointStr = pointArr[i].split(",");
            double lat = Double.parseDouble(pointStr[0]);
            double lon = Double.parseDouble(pointStr[1]);
            Point point = new Point(lat, lon, SpatialReferences.getWgs84());
            points.add(point);
        }
        drawArcgisLine(points);
    }


    private void showPolygon(String[] pointArr) {
        if (pointArr.length == 0) {
            return;
        }
        List<Point> points = new ArrayList<>();
        for (int i = 0; i < pointArr.length; i++) {
            String[] pointStr = pointArr[i].split(",");
            double lat = Double.parseDouble(pointStr[0]);
            double lon = Double.parseDouble(pointStr[1]);
            Point point = new Point(lat, lon);
            points.add(point);
        }
        drawArcGisFill(points);
    }

    /**
     * map画线
     */
    private void drawArcgisLine(List<Point> points) {
        PointCollection pointCollection = new PointCollection(points);
        Polyline mPolyline = new Polyline(pointCollection);//点画线，mPoints为坐标集合
        GraphicsOverlay graphicsOverlayPump = new GraphicsOverlay();
        mapView.getGraphicsOverlays().add(graphicsOverlayPump);
        SimpleLineSymbol lineSym = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorAccent), 2);
        Graphic graphicTrail = new Graphic(mPolyline, lineSym);
        graphicsOverlayPump.getGraphics().add(graphicTrail);
    }

    /**
     * map画面
     */
    private void drawArcGisFill(List<Point> points) {
        PolygonBuilder polygonGeometry = new PolygonBuilder(SpatialReferences.getWgs84());
        for (Point pd : points) {
            polygonGeometry.addPoint(pd.getX(), pd.getY());
        }
        // solid yellow polygon symbol
        SimpleFillSymbol polygonSymbol =
                new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getResources().getColor(R.color.task_status_unfinished1), null);
        // create graphic for polygon
        Graphic polygonGraphic = new Graphic(polygonGeometry.toGeometry());
        // create graphic overlay for polygon
        GraphicsOverlay polygonGraphicOverlay = new GraphicsOverlay();
        // create simple renderer
        SimpleRenderer polygonRenderer = new SimpleRenderer(polygonSymbol);
        // add graphic to overlay
        polygonGraphicOverlay.setRenderer(polygonRenderer);
        // add graphic to overlay
        polygonGraphicOverlay.getGraphics().add(polygonGraphic);
        // add graphics overlay to MapView
        mapView.getGraphicsOverlays().add(polygonGraphicOverlay);
    }

    public void showShp(String shpPath) {
        String str = getJson(shpPath);
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONArray jsonArray = jsonObject.getJSONArray("features");
            if (jsonArray.length() == 0) {
                Log.e("wangchao", "jsonArray.length() == 0");
                return;
            }
            Log.e("wangchao", "jsonArray.length() > 0");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
                JSONObject jsonObject2 = (JSONObject) jsonObject1.get("geometry");
                String jsonType = jsonObject2.getString("type");
                if ("Polygon".equals(jsonType)) {
                    Log.e("wangchao", "Polygon");
                    JSONArray polygonArray = jsonObject2.getJSONArray("coordinates");
                    for (int a = 0; a < polygonArray.length(); a++) {
                        List<Point> polygonPoints = new ArrayList<>();
                        JSONArray polygonPointArr = (JSONArray) polygonArray.get(a);
                        for (int s = 0;s < polygonPointArr.length();s++){
                            String polygonPoint = polygonPointArr.get(s).toString();
                            String aaa = polygonPoint.substring(1, polygonPoint.length() - 1);
                            String[] pointArr = aaa.split(",");
                            if (pointArr.length == 2) {
                                Point mapPoint = new Point(Double.parseDouble(pointArr[0]), Double.parseDouble(pointArr[1]), SpatialReference.create(4326));
                                polygonPoints.add(mapPoint);
                            }
                        }
                        drawArcGisFill(polygonPoints);
                    }
                } else if ("LineString".equals(jsonObject2.get("type"))) {
                    Log.e("wangchao", "LineString");
                    JSONArray lineStringArray = jsonObject2.getJSONArray("coordinates");
                    List<Point> linePoints = new ArrayList<>();
                    for (int a = 0; a < lineStringArray.length(); a++) {
                        String linePoint = lineStringArray.get(a).toString();
                        String aaa = linePoint.substring(1, linePoint.length() - 1);
                        String[] pointArr = aaa.split(",");
                        if (pointArr.length == 2) {
                            Point mapPoint = new Point(Double.parseDouble(pointArr[0]), Double.parseDouble(pointArr[1]), SpatialReference.create(4326));
                            linePoints.add(mapPoint);
                        }
                    }
                    drawArcgisLine(linePoints);
                } else if ("Point".equals(jsonObject2.get("type"))) {
                    Log.e("wangchao", "Point");
                    String pointStr = jsonObject2.getString("coordinates");
                    String aaa = pointStr.substring(1, pointStr.length() - 1);
                    Log.e("wangchao", "Point = " + aaa);
                    String[] pointArr = aaa.split(",");
                    if (pointArr.length == 2) {
                        Point mapPoint = new Point(Double.parseDouble(pointArr[0]), Double.parseDouble(pointArr[1]), SpatialReference.create(4326));
                        loadUnitMarkerData(mapPoint);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void showKml(String shpPath) {
        File file = Environment.getExternalStorageDirectory();
        shpPath = "http://127.0.0.1:8080" + shpPath.replace(file.getPath(), "");
        Log.e("wangchoa", shpPath);
        KmlDataset forecastKmlDataset = new KmlDataset(shpPath);
        KmlLayer forecastKmlLayer = new KmlLayer(forecastKmlDataset);
        map.getOperationalLayers().add(forecastKmlLayer);
    }

    public String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            /* 将字节数组转换成字符创， 并转换编码的格式 */
            String res = new String(buffer, "UTF-8");
            stringBuilder.append(res);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }

    /**
     * 加载地图marker元素数据
     */
    private void loadUnitMarkerData(Point point) {
        MarkerSymbol mMarkerSymbol = new SimpleMarkerSymbol(
                SimpleMarkerSymbol.Style.CIRCLE,
                Color.BLUE, 5
        );
        //添加点
        GraphicsOverlay graphicsOverlayPump = new GraphicsOverlay();
        mapView.getGraphicsOverlays().add(graphicsOverlayPump);
        graphicsOverlayPump.getGraphics().add(new Graphic(point, new HashMap<String, Object>(), mMarkerSymbol));
    }
}
